package com.fitz.registry.zookeepper;

import com.fitz.common.Constant;
import com.fitz.registry.DefaultRegistry;
import com.fitz.registry.InstanceInfo;
import com.fitz.registry.InstanceRegistry;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author fitz 2020-5-14 14:53
 */
@Slf4j
public class ZookeeperRegistry extends DefaultRegistry implements InstanceRegistry {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperRegistry.class);

    private final CountDownLatch latch = new CountDownLatch(1);

    private volatile List<InstanceInfo> instances = new ArrayList<>();

    private final String registryAddress;

    private ZooKeeper zooKeeper;

    public ZookeeperRegistry(String registryAddress) {
        this.registryAddress = registryAddress;
        if (zooKeeper == null) {
            zooKeeper = connectServer();
        }
        watchNode(zooKeeper);
    }

    private ZooKeeper connectServer() {
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (event.getState() == Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                }
            });
            latch.await();
        } catch (IOException | InterruptedException e) {
            LOGGER.error("", e);
        }
        return zk;
    }

    //TODO
    private void createNode(ZooKeeper zk, String data) {
        try {
            byte[] bytes = data.getBytes();
            if (null == zk.exists(Constant.ZK_REGISTRY_PATH,false)){
                zk.create(Constant.ZK_REGISTRY_PATH,"1".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
            }
            if (null == zk.exists(Constant.ZK_DATA_PATH,false)){
                zk.create(Constant.ZK_DATA_PATH,"1".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
            }
            String path = zk.create(Constant.ZK_SERVER_ADDRESS, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            LOGGER.debug("create zookeeper node ({} => {})", path, data);
        } catch (KeeperException | InterruptedException e) {
            LOGGER.error("", e);
        }
    }

    private void watchNode(final ZooKeeper zk) {
        try {
            List<String> nodeList = zk.getChildren(Constant.ZK_DATA_PATH, event -> {
                if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
                    System.out.print("path="+event.getPath()+"    NodeChildrenChanged");
                    watchNode(zk);
                }
                if(event.getType()== Watcher.Event.EventType.NodeDeleted){
                    System.out.print("path="+event.getPath()+"    临时节点被删除了。。");
                }
            });
            List<InstanceInfo> dataList = new ArrayList<>();
            for (String node : nodeList) {
                byte[] bytes = zk.getData(Constant.ZK_DATA_PATH + "/" + node, false, null);
                String address = new String(bytes);
                String[] array = address.split(":");
                InstanceInfo instanceInfo = new InstanceInfo();
                instanceInfo.setHost(array[0]);
                instanceInfo.setPort(Integer.parseInt(array[1]));
                dataList.add(instanceInfo);
            }
            System.out.println("监听到新的节点:");
            log.debug("node data: {}", dataList);
            instances = dataList;
        } catch (KeeperException | InterruptedException e) {
            log.error("", e);
        }
    }

    @Override
    public void register(InstanceInfo instance) {
        String data = instance.getHost()+":"+instance.getPort();
        if (zooKeeper == null) {
            zooKeeper = connectServer();
        }
        createNode(zooKeeper, data);
    }

    @Override
    public void deRegister(InstanceInfo instance) {

    }

    @Override
    public List<InstanceInfo> getAllInstances(String serviceName) {
        return instances;
    }

    @Override
    public void subscribe(String serviceName) {

    }

    @Override
    public void unSubscribe(String serviceName) {

    }
}
